Skip to content
This repository has been archived by the owner on Sep 1, 2020. It is now read-only.

Latest commit

 

History

History
58 lines (41 loc) · 1.57 KB

7.3.9 - Http/Response->detach.md

File metadata and controls

58 lines (41 loc) · 1.57 KB

Http\Response->detach

分离响应对象。使用此方法后,$response对象销毁时不会自动end,与Http\Response::createServer::send配合使用。

function Http\Response->detach();
  • 客户端已完成响应,操作失败返回false,成功返回true

需要2.2.0或更高版本

跨进程响应

某些情况下,需要在Task进程中对客户端发出响应。这时可以利用detach使$response对象独立。在Task进程可以重新构建$response,发起Http请求响应。

$http = new swoole_http_server("0.0.0.0", 9501);

$http->set(['task_worker_num' => 1, 'worker_num' => 1]);

$http->on('request', function ($req, Swoole\Http\Response $resp) use ($http) {
    $resp->detach();
    $http->task(strval($resp->fd));
});

$http->on('finish', function ()
{
    echo "task finish";
});

$http->on('task', function ($serv, $task_id, $worker_id, $data)
{
    var_dump($data);
    $resp = Swoole\Http\Response::create($data);
    $resp->end("in task");
    echo "async task\n";
});

$http->start();

发送任意内容

某些特殊的场景下,需要对客户端发送特殊的响应内容。Http\Response对象自带的end方法无法满足需求,可以使用detach分离响应对象,然后自行组包并使用Server::send发送数据。

$http = new swoole_http_server("0.0.0.0", 9501);

$http->on('request', function ($req, Swoole\Http\Response $resp) use ($http) {
    $resp->detach();
    $http->send($resp->fd, "HTTP/1.1 200 OK\r\nServer: server\r\n\r\nHello World\n");
});

$http->start();